package com.shoplink.launcher;

import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.Status;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.ActionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.preference.PreferenceFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.shoplink.launcher.WifiAdapter.IonPswEorrListener;
import com.shoplink.view.AnimatedSelector;
import com.shoplink.view.MyToast;

public class WifiSettingFragment extends PreferenceFragment implements
		View.OnClickListener {

	private IntentFilter mFilter;

	private BroadcastReceiver mReceiver;

	private Scanner mScanner;

	private WifiManager mWifiManager;

	private WifiInfo mLastInfo;

	private int mLastPriority;

	private boolean mResetNetworks = false;

	private int mKeyStoreNetworkId = -1;

	private AccessPoint mSelected;

	private WifiDialog mDialog;

	private ConfirmDialog mConfirmDialog;

	private ListView wifiListView;

	private boolean isConnecting = false;

	private WifiManager.ActionListener mConnectListener;

	private WifiManager.ActionListener mSaveListener;

	private boolean isFromSetting = false;

	private WifiAdapter adapter;

	private ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();

	private ArrayList<AccessPoint> accessPointsTemp = new ArrayList<AccessPoint>();

	private String addSsid;

	private final String TAG = "wifiactivity";

	private static int netWorkId = -1;

	private final int WIFI_CONNECTED_MSG = 800;

	private final int WIFI_OPENLISTKEY_MSG = 1000;

	private final int WIFI_CONNECTED_MSG_2 = 900;

	private final int WIFI_LISTVIEW_SETSELECTOR = 600;

	private final int REFRESH_WIFILIST_MSG = 700;

	private AnimatedSelector animatedSelector;

	private int listItemHight, lineHight;

	private View selector;

	private boolean isAddNetWork = false;

	private boolean openKey;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == REFRESH_WIFILIST_MSG) {
				refreshAccessPoints(0);
				return;
			}
			if (msg.what == WIFI_LISTVIEW_SETSELECTOR) {
				setSelector(wifiListView);
				return;
			} else if (msg.what == WIFI_CONNECTED_MSG) {
				if (NetworkUtils.isNetworkConnected(getActivity())) {
					connectedSuccess();
					MyToast.makePrompt(
							getActivity(),
							getString(R.string.toast_wifi_connect_ok_info)
									+ NetworkUtils
											.getNetworkName(getActivity()))
							.show();
				} else {
					removeMessages(WIFI_CONNECTED_MSG);
					sendEmptyMessageDelayed(WIFI_CONNECTED_MSG, 500);
				}
			} else if (msg.what == WIFI_CONNECTED_MSG_2) {
				connectedSuccess();
			} else if (WIFI_OPENLISTKEY_MSG == msg.what) {
				openKey = true;
			}

		}
	};

	public void resiger() {
		mFilter = new IntentFilter();
		mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
		mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
		mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				System.out.println("====================" + intent.getAction());
				handleEvent(intent);
			}
		};
		mScanner = new Scanner();
		mScanner.resume();
	}

	private void handleEvent(Intent intent) {
		String action = intent.getAction();
		if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
			NetworkInfo info = ((NetworkInfo) intent
					.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO));
			DetailedState state = info.getDetailedState();
			WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
			/**
			 * 连接wifi实时刷新wifi状�?
			 */
			for (int i = 0; i < adapter.getCount(); i++) {
				AccessPoint accessPoint = adapter.getItem(i);
				if (accessPoint != null) {
					accessPoint.setWifiState(null);
					String ssid = wifiInfo.getSSID();
					if (!TextUtils.isEmpty(ssid)) {
						if (accessPoint.getTitle().equals(
								ssid.substring(1, ssid.length() - 1))) {
							Log.i(TAG, "===================in");
							accessPoint.setWifiState(state);
							// break;
						}
					}
				}
			}

			adapter.notifyDataSetChanged();
			if (state == DetailedState.CONNECTED) {
				mHandler.removeMessages(WIFI_CONNECTED_MSG_2);
				mHandler.sendEmptyMessageDelayed(WIFI_CONNECTED_MSG_2, 500);
			}
			Log.i(TAG, "==========" + wifiInfo.getSSID());
			Log.i(TAG, "==========" + state);
		} else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {

		} else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
			// if (intent.getIntExtra("supplicantError", 0) == 1) {//
			// 连接出错刷新wifi状�?
			if (mSelected != null) {
				AccessPoint accessPoint = getCurrentAcessState(mSelected);
				if (accessPoint == null) {
					return;
				}
				adapter.refreshItem(accessPoint);
				if (accessPoint.getConfig() != null) {
					Log.i(TAG, "================e1"
							+ accessPoint.getConfig().disableReason);
				}
			}

		} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
			if (accessPoints.size() <= 1) {
				updateAccessPoints(2);
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
				.penaltyLog().build());
		resiger();
		listItemHight = (int) getActivity().getResources().getDimension(
				R.dimen.wifi_list_item_hight);
		lineHight = (int) getActivity().getResources().getDimension(
				R.dimen.wifi_list_line_hight);
		isFromSetting = getActivity().getIntent().getBooleanExtra(
				NetworkUtils.FROM_SETTINGS, false);
		mWifiManager = (WifiManager) getActivity().getSystemService(
				Context.WIFI_SERVICE);

		mConnectListener = new WifiManager.ActionListener() {
			@Override
			public void onSuccess() {
				mHandler.removeMessages(WIFI_CONNECTED_MSG);
				mHandler.sendEmptyMessageDelayed(WIFI_CONNECTED_MSG, 500);
			}

			@Override
			public void onFailure(int reason) {
			}
		};
		mSaveListener = new WifiManager.ActionListener() {
			@Override
			public void onSuccess() {
				mHandler.removeMessages(WIFI_CONNECTED_MSG);
				mHandler.sendEmptyMessageDelayed(WIFI_CONNECTED_MSG, 500);
			}

			@Override
			public void onFailure(int reason) {

			}
		};

		View view = inflater.inflate(R.layout.wifi_setting_layout, container,
				false);
		wifiListView = (ListView) view.findViewById(R.id.listview);
		adapter = new WifiAdapter(getActivity(), accessPoints);
		adapter.setOnPswErorrListener(new IonPswEorrListener() {

			@Override
			public void onErorr(int nid) {
				// TODO Auto-generated method stub
				mWifiManager.disableNetwork(nid);
				mWifiManager.removeNetwork(nid);
				mHandler.sendEmptyMessageDelayed(REFRESH_WIFILIST_MSG, 1000);
			}
		});
		wifiListView.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (!openKey) {
					return true;
				}
				return false;
			}
		});
		wifiListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// refreshAccessPoints();
				mSelected = adapter.getItem(position);
				if (TextUtils.isEmpty(mSelected.ssid)) {
					mSelected = null;
				}
				showDialog(mSelected, false);
			}
		});
		wifiListView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		wifiListView.setAdapter(adapter);
		wifiListView.setNextFocusUpId(wifiListView.getId());
		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		selector = parent.findViewById(R.id.selector);
		// initDialogDimen(wifiListView, 6, parent);

		// registerForContextMenu(preferenceList);
		mWifiManager.setWifiEnabled(true);
		mWifiManager.startScan();
		wifiListView.requestFocus();
		updateAccessPoints(1);
		wifiListView.smoothScrollToPosition(0);
		mHandler.sendEmptyMessageDelayed(WIFI_LISTVIEW_SETSELECTOR, 300);
		return view;
	}

	public void initDialogDimen(ListView listView, int conut,
			RelativeLayout parent) {

		RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) listView
				.getLayoutParams();
		params.height = (listItemHight + lineHight) * conut;
		listView.setLayoutParams(params);

		FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) parent
				.getLayoutParams();
		params2.height = (listItemHight + lineHight) * conut;
		parent.setLayoutParams(params2);
	}

	public void setSelector(ListView listView) {
		if (getActivity() == null) {
			return;
		}
		animatedSelector = new AnimatedSelector(selector,
				listView.getSelector());
		animatedSelector.setTopOffset(getResources().getDimensionPixelOffset(
				R.dimen.wifi_list_selector_topoffset));
		animatedSelector.setHightOffset(getResources().getDimensionPixelOffset(
				R.dimen.wifi_list_selector_hightoffset));
		animatedSelector
				.setmWidthOffset(getResources().getDimensionPixelOffset(
						R.dimen.wifi_list_selector_widthffset));
		animatedSelector.setLeftOffset(getResources().getDimensionPixelOffset(
				R.dimen.wifi_list_selector_leftoffset));
		animatedSelector.hideView();
		listView.setSelector(animatedSelector);
	}

	@Override
	public void onResume() {
		super.onResume();
		getActivity().registerReceiver(mReceiver, mFilter);
		mHandler.sendEmptyMessageDelayed(WIFI_OPENLISTKEY_MSG, 1000);
		if (mKeyStoreNetworkId != -1 /*
									 * && KeyStore.getInstance().test() ==
									 * KeyStore.NO_ERROR
									 */) {
			connect(mKeyStoreNetworkId);
		}
		mKeyStoreNetworkId = -1;
		if (wifiListView != null) {
			wifiListView.requestFocus();
			wifiListView.setSelection(0);
		}
	}

	private void clearAcessState() {
		for (int i = 0; i < adapter.getCount(); i++) {
			adapter.getItem(i).setConnecting(false);
			adapter.getItem(i).setWifiState(null);
		}
	}

	public void clearCurrentState(AccessPoint accessPoint) {
		for (int i = 0; i < adapter.getCount(); i++) {
			if (adapter.getItem(i).ssid.equals(accessPoint.ssid)) {
				adapter.getItem(i).setWifiState(null);
				adapter.getItem(i).setConnecting(false);
				adapter.getItem(i).setWifiConfig(null);
				adapter.getItem(i).setWifiNetId(-1);
				break;
			}
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		getActivity().unregisterReceiver(mReceiver);
		mScanner.pause();
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		if (mConfirmDialog != null) {
			mConfirmDialog.dismiss();
			mConfirmDialog = null;
		}
		// if (mResetNetworks) {
		// enableNetworks();
		// }
	}

	private void submitWifiConfiguration(WifiConfiguration config) {
		if (config == null) {
			if (mSelected != null && mSelected.networkId != INVALID_NETWORK_ID) {
				if (netWorkId != -1) {
					disconnectWifi(netWorkId);

				}
				clearAcessState();
				netWorkId = mSelected.networkId;
				mSelected.setConnecting(true);
				adapter.notifyDataSetChanged();
				mWifiManager.connect(mSelected.networkId, mConnectListener);
			}
		} else if (config.networkId != INVALID_NETWORK_ID) {
			if (mSelected != null) {
				mWifiManager.save(config, mSaveListener);
			}
		} else {
			clearAcessState();
			if (mSelected != null) {
				mSelected.setConnecting(true);
				adapter.notifyDataSetChanged();
			} else {
				addSsid = config.SSID;
				addSsid = addSsid.substring(1, addSsid.length() - 1);
			}
			mWifiManager.connect(config, mConnectListener);
		}

		mHandler.sendEmptyMessage(REFRESH_WIFILIST_MSG);
	}

	public WifiDialog getDialog() {
		return mDialog;
	}

	public void showDialog(AccessPoint accessPoint, boolean edit) {
		if (mDialog != null) {
			mDialog.dismiss();
		}
		mDialog = new WifiDialog(getActivity(), this, accessPoint, edit);
		Window dialogWindow = mDialog.getWindow();
		mDialog.show();
		dialogWindow.setGravity(Gravity.CENTER);
		LayoutParams p = dialogWindow.getAttributes();
		p.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(p);
	}

	public void showConfirmDialog(String ssid) {
		if (mConfirmDialog != null) {
			mConfirmDialog.dismiss();
		}
		if (ssid == null) {
			ssid = " ";
		} else {
			ssid = String.format(getString(R.string.forget_confirm), ssid);
		}
		ssid += "\n" + getString(R.string.forget_confirm_info);
		mConfirmDialog = new ConfirmDialog(getActivity(), this, ssid);
		mConfirmDialog.show();
	}

	/**
	 * 忽略掉网�?
	 * 
	 * @param networkId
	 * @param isRefresh
	 *            //当手动添加的ssid网络不存在的时�?就传入false忽略的时候不刷新状�?
	 */
	private void forget(int networkId, boolean isRefresh) {
		mWifiManager.disconnect();
		// mWifiManager.disableNetwork(networkId);
		mWifiManager.removeNetwork(networkId);
		mWifiManager.forget(networkId, null);
		if (isRefresh) {
			clearCurrentState(mSelected);
		}
		saveNetworks(isRefresh);
	}

	private void connect(int networkId) {
		if (networkId == -1) {
			return;
		}
		// Reset the priority of each network if it goes too high.
		if (mLastPriority > 1000000) {
			// for (int i = mAccessPoints.getPreferenceCount() - 1; i >= 0; --i)
			// {
			// if (mAccessPoints.getPreference(i) instanceof AccessPoint) {
			// AccessPoint accessPoint = (AccessPoint) mAccessPoints
			// .getPreference(i);
			// if (accessPoint.networkId != -1) {
			// WifiConfiguration config = new WifiConfiguration();
			// config.networkId = accessPoint.networkId;
			// config.priority = 0;
			// mWifiManager.updateNetwork(config);
			// }
			// }
			//
			// }
			// mLastPriority = 0;
		}

		// Set to the highest priority and save the configuration.
		WifiConfiguration config = new WifiConfiguration();
		config.networkId = networkId;
		config.priority = ++mLastPriority;
		mWifiManager.updateNetwork(config);
		saveNetworks(false);

		// Connect to network by disabling others.
		mWifiManager.enableNetwork(networkId, true);
		mWifiManager.reconnect();
		mResetNetworks = true;
	}

	private void enableNetworks() {

		for (int i = 0; i < adapter.getCount(); i++) {
			WifiConfiguration config = adapter.getItem(i).getConfig();
			if (config != null && config.status != Status.ENABLED) {
				mWifiManager.enableNetwork(config.networkId, false);
			}
		}

		mResetNetworks = false;
	}

	private void saveNetworks(boolean isRemove) {
		// Always save the configuration with all networks enabled.
		enableNetworks();
		mWifiManager.saveConfiguration();
		if (isRemove) {
			refreshAccessPoints(2);
		}
	}

	/**
	 * 获取当前acesspoint状�?
	 * 
	 * @param acesp
	 * @return
	 */
	public AccessPoint getCurrentAcessState(AccessPoint acesp) {
		AccessPoint accessPoint = null;
		ArrayList<AccessPoint> points = new ArrayList<AccessPoint>();
		scanAccessPoint(points);
		for (int i = 0; i < points.size(); i++) {
			if (acesp.ssid.equals(points.get(i).ssid)) {
				accessPoint = points.get(i);
				break;
			}
		}
		return accessPoint;
	}

	private void updateAccessPoints(int num) {
		accessPoints.clear();
		mLastInfo = mWifiManager.getConnectionInfo();
		scanAccessPoint(accessPoints);

		String ssid = mLastInfo.getSSID();
		if (!TextUtils.isEmpty(ssid)) {
			ssid = ssid.substring(1, ssid.length() - 1);
			if (!ssid.equals("")) {
				for (int n = 0; n < accessPoints.size(); n++) {
					if (ssid.equals(accessPoints.get(n).ssid)) {
						AccessPoint tempAccess = accessPoints.get(0);
						accessPoints.set(0, accessPoints.get(n));
						accessPoints.set(n, tempAccess);
						break;
					}
				}
			}
		}
		adapter.notifyDataSetChanged();
	}

	/**
	 * 专门用于获取wifi
	 * 
	 * @param accessList
	 */
	public void scanAccessPoint(ArrayList<AccessPoint> accessList) {
		List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();

		if (configs != null) {
			Log.i(TAG, "=============size==" + configs.size());
			mLastPriority = 0;
			for (WifiConfiguration config : configs) {
				System.out.println("=================configInfo==>"
						+ config.SSID);
				if (config.priority > mLastPriority) {
					mLastPriority = config.priority;
				}

				// Shift the status to make enableNetworks() more efficient.
				if (config.status == Status.CURRENT) {
					config.status = Status.ENABLED;
				} else if (config.status == Status.DISABLED) {
					config.status = Status.CURRENT;
				}
				AccessPoint accessPoint = new AccessPoint(getActivity(), config);
				// accessPoint.update(mLastInfo, mLastState);
				accessList.add(accessPoint);
			}
		}

		List<ScanResult> results = mWifiManager.getScanResults();

		if (results == null || results.size() == 0) {
			if (configs != null) {
				configs.clear();
				accessList.clear();
			}
		}

		if (results != null) {
			Log.i(TAG, "=============size==" + results.size());

			if (!TextUtils.isEmpty(addSsid)) {
				isAddNetWork = true;
				new AddNetWorkFilter(results, accessList, configs)
						.executeOnExecutor(Executors.newCachedThreadPool());
				return;
			}
			assembleWifiList(results, accessList);
		}

	}

	class AddNetWorkFilter extends
			AsyncTask<Void, Void, ArrayList<AccessPoint>> {

		private List<ScanResult> results;
		private ArrayList<AccessPoint> accessList;
		private List<WifiConfiguration> configs;

		public AddNetWorkFilter(List<ScanResult> results,
				ArrayList<AccessPoint> accessList,
				List<WifiConfiguration> configs) {
			this.results = results;
			this.accessList = accessList;
			this.configs = configs;
		}

		@Override
		protected ArrayList<AccessPoint> doInBackground(Void... params) {
			// 用来比对不存在的ssid
			LinkedList<String> resultSsids = new LinkedList<String>();
			resultSsids.clear();
			int scanCount = 6;
			// 扫描10秒钟看看有没有手动添加的网络
			while (scanCount > 0) {
				results = mWifiManager.getScanResults();
				resultSsids.clear();
				// 填充
				for (ScanResult result : results) {
					if (result.SSID == null || result.SSID.length() == 0
							|| result.capabilities.contains("[IBSS]")) {
						continue;
					}
					Log.i(TAG, ">>>>>>>>>>>>>>add>>>>" + result.SSID);
					resultSsids.add(result.SSID);
				}
				if (resultSsids.contains(addSsid)) {
					scanCount = -1;
				}
				--scanCount;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			// �?��比对如果存在就删�?
			for (int i = 0; i < configs.size(); i++) {
				String ssid = configs.get(i).SSID.substring(1,
						configs.get(i).SSID.length() - 1);
				if (!resultSsids.contains(ssid)) {
					Log.i(TAG, ">>>>>>>>>>>>>>remove>>>>" + configs.get(i).SSID);
					for (int j = 0; j < accessList.size(); j++) {
						if (accessList.get(j).ssid.equals(ssid)) {
							Log.i(TAG, ">>>>>>>>>>>>>>"
									+ accessList.get(j).networkId);
							Log.i(TAG, ">>>>>>>>>>>>>>"
									+ accessList.get(j).getLevel());
							accessList.remove(j);
							forget(configs.get(i).networkId, false);//
							// 不存在的就忽略掉
							if (!TextUtils.isEmpty(addSsid)
									&& addSsid.equals(ssid)) {
								addSsid = null;
							}
						}
					}

				}
			}
			return accessList;
		}

		@Override
		protected void onPostExecute(ArrayList<AccessPoint> result) {
			if (TextUtils.isEmpty(addSsid)) {
				MyToast.makePrompt(getActivity(),
						getActivity().getString(R.string.ssid_not_find)).show();
			}
			assembleWifiList(results, accessList);
			/**
			 * 刷新数据
			 */
			for (int i = 0; i < accessPointsTemp.size(); i++) {
				for (int j = 0; j < accessPoints.size(); j++) {
					if (accessPointsTemp.get(i).ssid
							.equals(accessPoints.get(j).ssid)) {
						Log.d(TAG, "===========" + accessPointsTemp.get(i).ssid
								+ "============>"
								+ accessPointsTemp.get(i).getLevel());
						accessPoints.get(j).setAllResult(
								accessPointsTemp.get(i).mScanResult,
								accessPointsTemp.get(i).getConfig(),
								accessPointsTemp.get(i).networkId);
					}
				}
			}

			/**
			 * 找出手动添加的网�?
			 */
			for (int i = accessPointsTemp.size() - 1; i >= 0; i--) {
				boolean isDiff = false;
				for (int j = 0; j < accessPoints.size(); j++) {

					if (accessPointsTemp.get(i).ssid
							.equals(accessPoints.get(j).ssid)) {
						isDiff = true;
					}

					if (j == (accessPoints.size() - 1) && !isDiff) {
						if (!TextUtils.isEmpty(addSsid)
								&& addSsid.equals(accessPointsTemp.get(i).ssid)) {
							accessPointsTemp.get(i).setConnecting(true);
							accessPoints.add(0, accessPointsTemp.get(i));
							mSelected = accessPointsTemp.get(i);
							addSsid = null;
							Log.i(TAG,
									"=============add="
											+ accessPointsTemp.get(i).ssid);
							wifiListView.setSelection(0);
						}
						break;
					}

				}
			}

			// if (num == 3) {// 仅仅连接上后进行排序
			/**
			 * 连接上的ssid插入第一�?
			 */
			mLastInfo = mWifiManager.getConnectionInfo();
			if (mLastInfo != null) {
				String ssid = mLastInfo.getSSID();
				if (!TextUtils.isEmpty(ssid)) {
					ssid = ssid.substring(1, ssid.length() - 1);
					for (int i = 0; i < accessPoints.size(); i++) {
						if (!ssid.equals("")) {
							if (ssid.equals(accessPoints.get(i).ssid)) {
								AccessPoint tempAccess = accessPoints.get(0);
								accessPoints.set(0, accessPoints.get(i));
								accessPoints.set(i, tempAccess);
								break;
							}
						}
					}
				}
				// }
			}

			adapter.notifyDataSetChanged();
			super.onPostExecute(result);
		}
	}

	/**
	 * 组装wifi列表
	 */
	public void assembleWifiList(List<ScanResult> results,
			ArrayList<AccessPoint> accessList) {

		if (results != null) {
			/**
			 * 清除连接过的但又没有扫描出来的accesspoint
			 */
			boolean isExist = false;
			for (int i = 0; i < accessList.size(); i++) {
				System.out.println(">>>>>>>>>>>>>>>>>>config ssid>"
						+ accessList.get(i).ssid);
				isExist = false;
				for (int j = 0; j < results.size(); j++) {
					System.out.println(">>>>>>>>>>>>>>>>>>all ssid>"
							+ results.get(i).SSID);
					if (accessList.get(i).ssid.equals(results.get(j).SSID)) {
						isExist = true;
					}
					if (j == results.size() - 1 && !isExist) {
						System.out.println("===============remove config="
								+ accessList.get(i).ssid);
						accessList.remove(i);
						i--;
					}
				}
			}

			for (ScanResult result : results) {
				// Ignore hidden and ad-hoc networks.
				if (result.SSID == null || result.SSID.length() == 0
						|| result.capabilities.contains("[IBSS]")) {
					continue;
				}
				boolean found = false;
				for (AccessPoint accessPoint : accessList) {
					if (accessPoint.update(result)) {
						found = true;
						// if (accessPoint.getLevel() < 0) {
						// Log.i(TAG, ">>>>>>>>>>>>>>levle < 0>"
						// + accessPoint.ssid);
						// accessList.remove(accessPoint);
						// break;
						// }
					}
				}
				if (!found) {
					AccessPoint accessp = new AccessPoint(getActivity(), result);
					accessList.add(accessp);
				}

			}
			// 如果有信号强度为-1的就忽略�?
			for (int i = 0; i < accessList.size(); i++) {
				Log.i(TAG, "wifi ssid ====>" + accessList.get(i).ssid);
				if (accessList.get(i).getLevel() < 0) {
					// forget(accessList.get(i).networkId, false);//
					// accessList.remove(i);
				}
			}
		}
		AccessPoint addNetWork = new AccessPoint();
		addNetWork.ssid = "";
		accessList.add(addNetWork);
	}

	/**
	 * 当网络改变之后就刷新列AccessPoint
	 */
	private void refreshAccessPoints(int num) {
		Log.i(TAG, "===refresh===" + num);
		mLastInfo = mWifiManager.getConnectionInfo();
		accessPointsTemp.clear();
		scanAccessPoint(accessPointsTemp);

		/**
		 * 如果是在查找是否有添加网络就不往下执�?
		 */
		if (isAddNetWork) {
			isAddNetWork = false;
			return;
		}

		/**
		 * 刷新数据
		 */
		for (int i = 0; i < accessPointsTemp.size(); i++) {
			for (int j = 0; j < accessPoints.size(); j++) {
				if (accessPointsTemp.get(i).ssid
						.equals(accessPoints.get(j).ssid)) {
					Log.d(TAG,
							"shop ===========" + accessPointsTemp.get(i).ssid
									+ "    net id============>"
									+ accessPointsTemp.get(i).networkId);
					accessPoints.get(j).setAllResult(
							accessPointsTemp.get(i).mScanResult,
							accessPointsTemp.get(i).getConfig(),
							accessPointsTemp.get(i).networkId);
				}
			}
		}

		/**
		 * 找出手动添加的网�?
		 */
		for (int i = accessPointsTemp.size() - 1; i >= 0; i--) {
			boolean isDiff = false;
			for (int j = 0; j < accessPoints.size(); j++) {

				if (accessPointsTemp.get(i).ssid
						.equals(accessPoints.get(j).ssid)) {
					isDiff = true;
				}

				if (j == (accessPoints.size() - 1) && !isDiff) {
					if (!TextUtils.isEmpty(addSsid)
							&& addSsid.equals(accessPointsTemp.get(i).ssid)) {
						accessPointsTemp.get(i).setConnecting(true);
						accessPoints.add(0, accessPointsTemp.get(i));
						mSelected = accessPointsTemp.get(i);
						addSsid = null;
						Log.i(TAG,
								"=============add="
										+ accessPointsTemp.get(i).ssid);
						wifiListView.setSelection(0);
					} else {
						if (!TextUtils.isEmpty(accessPointsTemp.get(i).ssid)) {
							int index = 0;
							if (accessPoints.size() > 3) {
								index = accessPoints.size() - 2;
							} else if (accessPoints.size() > 1) {
								index = 1;
							}
							accessPoints.add(index, accessPointsTemp.get(i));
						}
					}

					break;
				}

			}
		}

		if (num == 3) {// 仅仅连接上后进行排序
			/**
			 * 连接上的ssid插入第一�?
			 */
			if (mLastInfo != null) {
				String ssid = mLastInfo.getSSID();
				if (!TextUtils.isEmpty(ssid)) {
					ssid = ssid.substring(1, ssid.length() - 1);
					for (int i = 0; i < accessPoints.size(); i++) {
						if (!ssid.equals("")) {
							if (ssid.equals(accessPoints.get(i).ssid)) {
								AccessPoint tempAccess = accessPoints.get(0);
								accessPoints.set(0, accessPoints.get(i));
								accessPoints.set(i, tempAccess);
								break;
							}
						}
					}
				}
			}
		}

		adapter.notifyDataSetChanged();
	}

	@Override
	public void onStop() {
		if (mScanner != null) {
			mScanner.pause();
		}

		super.onStop();
	}

	/**
	 * 断开
	 * 
	 * @param netId
	 */
	public void disconnectWifi(int netId) {

		mWifiManager.disableNetwork(netId);
		mWifiManager.disconnect();
	}

	private class Scanner extends Handler {

		private int mRetry = 0;

		void resume() {
			if (!hasMessages(0)) {
				sendEmptyMessage(0);
			}
		}

		void pause() {
			mRetry = 0;
			removeMessages(0);
		}

		@Override
		public void handleMessage(Message message) {
			if (mWifiManager.startScan()) {
				mRetry = 0;
				refreshAccessPoints(10);
			} else if (++mRetry >= 3) {
				mRetry = 0;
				Toast.makeText(getActivity(), R.string.wifi_fail_to_scan,
						Toast.LENGTH_LONG).show();
				return;
			}
			sendEmptyMessageDelayed(0, 15000);
		}
	}

	private void connectedSuccess() {
		refreshAccessPoints(3);
		wifiListView.setSelection(0);
	}

	@Override
	public void onClick(View button) {
		if (button != null && button.getId() == R.id.confirm_ok
				&& mSelected != null) {
			if (mConfirmDialog != null) {
				mConfirmDialog.dismiss();
			}
			forget(mSelected.networkId, true);
			isConnecting = false;
		} else if (button != null && button.getId() == R.id.confirm_cancel
				&& mSelected != null) {
			if (mConfirmDialog != null) {
				mConfirmDialog.dismiss();
			}
		} else if (button != null && button.getId() == R.id.button3
				&& mSelected != null) {
			showConfirmDialog(mSelected.ssid);
			// forget(mSelected.networkId);
			// isConnecting = false;
		} else if (button != null && button.getId() == R.id.button1
				&& mDialog != null) {
			WifiConfiguration config = mDialog.getConfig();
			submitWifiConfiguration(config);
			isConnecting = true;
		} else if (button != null && button.getId() == R.id.wifi_psw
				&& mDialog != null) {
			WifiConfiguration config = mDialog.getConfig();
			submitWifiConfiguration(config);
			isConnecting = true;
		} else {
			isConnecting = false;
		}
		if (mDialog != null) {
			mDialog.dismiss();
		}

	}

	@Override
	public void onDetach() {
		super.onDetach();

		try {
			Field childFragmentManager = Fragment.class
					.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);

		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}
